package com.ktjiaoyu.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktjiaoyu.server.config.security.JwtTokenUtil;
import com.ktjiaoyu.server.pojo.Admin;
import com.ktjiaoyu.server.service.IAdminService;
import com.ktjiaoyu.server.mapper.AdminMapper;
import com.ktjiaoyu.server.mapper.RoleMapper;
import com.ktjiaoyu.server.pojo.Role;
import com.ktjiaoyu.server.vo.RespBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jjx
 * @since 2024-07-10
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Resource
    UserDetailsService userDetailsService;
    @Resource
    PasswordEncoder passwordEncoder;
    @Resource
    JwtTokenUtil jwtTokenUtil;
    @Resource
    AdminMapper adminMapper;
    @Resource
    RoleMapper roleMapper;

    @Value("${jwt.tokenHead}")
    private String tokenHead; // application.yml中配置的JWT负载中拿到开头


    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest request) {
        //1.验证验证码
        String captcha=(String)request.getSession().getAttribute("captcha");
        if(code==null || !code.equalsIgnoreCase(captcha)){//验证码错误
            return RespBean.error("验证码不正确");
        }
        //
        //1.根据用户名查询用户信息
        Admin admin =null;
        try {
            admin = (Admin)userDetailsService.loadUserByUsername(username);
        } catch (Exception e) {
            return RespBean.error(e.getMessage());
        }

        //2.匹配密码
        if (!passwordEncoder.matches(password, admin.getPassword())) {
            return RespBean.error("用户名或密码错误");
        }

        //将用户信息保存到security
       /* UsernamePasswordAuthenticationToken upToken=
                new UsernamePasswordAuthenticationToken(admin,null,admin.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(upToken);*/

        //3.生成token
        String token = jwtTokenUtil.genegrateToken(admin);
        //响应前端
        Map<String,Object> map=new HashMap<>();
        map.put("token",token);
        map.put("tokenHead",tokenHead);
        map.put("avatar",admin.getUserFace());

        return RespBean.success("登录成功",map);
    }

    @Override
    public Admin getAdminByUserName(String userName) {
        QueryWrapper<Admin> qw=new QueryWrapper<>();
        qw.eq("username",userName);
        return adminMapper.selectOne(qw);
    }

    @Override
    public IPage<Admin> selectByPage(Page<Admin> page, String query, String sort) {
        QueryWrapper<Admin> qw=new QueryWrapper<>();
        qw.like("name",query)
            .or()
            .like("phone",query);
        Page<Admin> adminPage = adminMapper.selectPage(page, qw);
        return adminPage;

    }

    @Override
    public boolean saveAdmin(Admin admin) {
        int rs = adminMapper.insert(admin);
        if(rs>0){
            return true;
        }
        return false;
    }

    @Override
    public boolean updateAdmin(Admin admin) {
        int rs = adminMapper.updateById(admin);
        if(rs>0){
            return true;
        }
        return false;
    }

    @Override
    public List<Role> findRolesByAdminId(Integer id) {
        return adminMapper.findRolesByAdminId(id);
    }

    // 通过操作员用户ID查询其拥有菜单URL集合
    @Override
    public List<String> findMenuUrlByAdminId(Integer adminId) {
        return adminMapper.findMenuUrlByAdminId(adminId);
    }

}
